<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <!--<el-form-item label="部门" prop="deptId">
                <treeselect 
                    v-model="queryParams.deptId" 
                    :options="deptOptions" 
                    :show-count="true" 
                    placeholder="请选择部门" 
                    style="width: 240px"
                    size="small"
                />
            </el-form-item> -->
      <el-form-item label="关键字" prop="keywords">
        <el-input
          v-model="queryParams.keywords"
          placeholder="请输入姓名/手机号"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> 

    <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange" :border="true">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center" />
      <el-table-column label="ID" prop="userId" align="center" />
      <el-table-column label="姓名" prop="nickName" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="账号" prop="userName" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="所属部门" prop="dept.deptName" align="center" />
      <el-table-column label="手机号" prop="phonenumber" align="center" />
      <el-table-column label="角色" prop="roles.roleName" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="状态（启用/禁用）" align="center" key="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="显示顺序" prop="roleSort" align="center" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="100">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <!-- *姓名、*账号、*部门（树状）、*手机号、*角色（下拉） -->
      <el-form ref="form" :model="form" :rules="rules" :validate-on-rule-change="false" label-width="80px">
        <el-form-item label="姓名" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="账号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <!-- <treeselect v-model="form.deptId" :options="deptOptions" @input="deptIdChange" :show-count="true" placeholder="请选择归属部门" /> -->
          <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" />
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号" maxlength="11" />
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="form.roleIds" placeholder="请选择">
            <el-option
              v-for="item in roleOptions"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色顺序" prop="roleSort">
          <el-input-number v-model="form.roleSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核时间" prop="createTime">
          <el-date-picker clearable size="small"
            v-model="form.createTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择审核时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="图片" prop="img">
          <uploadImage v-model="form.img" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-button type="warning" plain size="mini" @click="importTemplate">下载模板</el-button>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
// import { getToken } from "@/utils/auth";
import UploadImage from '@/components/ImageUpload';

import tableData from "@/assets/json/adminSet.json";
import tableDataDetail from "@/assets/json/adminSetDetail.json";
import tree from "@/assets/json/tree.json";
import dict from "@/assets/json/dict.json";


export default {
  name: "adminSet",
  data() {
    return {
        /**查询 */
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          keywords: undefined,
        },
        // 显示搜索条件
        showSearch: true,
        /**功能按钮 */
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          // headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          // url: process.env.VUE_APP_BASE_API + "/system/user/importData",
          url: ''
        },
        /**表格展示 */
        // 遮罩层
        loading: true,
        // 表格数据
        tableList: [],
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        /** 弹框部分-------- */
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 表单参数
        form: {
          nickName: null,
          userName: null,
          deptId: null,
          phonenumber: null,
          roleIds: [],
          roleSort: 0,
        },
        // 表单校验
        rules: {
          nickName: [
            { required: true, message: "姓名不能为空", trigger: "blur" },
            { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
          ],
          userName: [
            { required: true, message: "账号不能为空", trigger: "blur" }
          ],
          deptId: [
            { required: true, message: "所属部门不能为空", trigger: "blur" }
          ],
          phonenumber: [
            { required: true, message: "手机号不能为空", trigger: "blur" },
            { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
          ],
          roleIds: [
            // { type:"array",required: true, message: '请至少选择一个角色', trigger: 'change' }
            // { required: true, message: '请至少选择一个角色', trigger: ['blur','change'] }
            { required: true, message: '角色不能为空', trigger: 'change' }
          ]
        },
        // 部门树选项
        deptOptions: undefined,
        // 角色选项
        roleOptions: [],
        // 状态数据字典
        statusOptions: [],
      
    };
  },
  components: {
    Treeselect,
    UploadImage
  },
  created() {
    this.getList();
    /* this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    }); */
    
    // 获取所属部门数据 树
    this.deptOptions = tree.data;
    // 获取所有角色数据 数组
    this.roleOptions = tableDataDetail.roles;
    // 获取角色状态字典
    this.statusOptions = dict.roles;
    
  },
  mounted() {

  },
  methods: {  
    /* deptIdChange(val) {
      this.$nextTick(() => {
        this.$refs.form.validateField('deptId');
      })
    }, */
    /** 筛选条件部分------------------- */
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 查询管理员列表 */
    getList() {
      console.log('getList---------------------');
      this.loading = true;
      // 调接口
      var res = tableData;
      this.tableList = res.rows;
      this.total = res.total;
      this.loading = false;
      /* listAdmin(this.queryParams).then(
        response => {
          this.tableList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      ); */
    },
    /** 表格展示部分------------------- */
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    // 状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.userName + '"吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.msgSuccess(text + "成功");
        })
      /* this.$confirm('确认要"' + text + '""' + row.userName + '"吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          // 调接口 改变状态值
          return changeRoleStatus(row.userId, row.status);
        }).then(() => {
          this.msgSuccess(text + "成功");
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        }); */
    },


    /** 功能按钮部分------------------- */
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
        this.reset();
        const userId = row.userId || this.ids
        // 调接口 获取对应管理员数据
        var res = tableDataDetail;
        this.form = res.data;
        this.form.roleIds = res.data.roleIds;
        this.open = true;
        this.title = "修改";
        /* getRole(userId).then(response => {
            this.form = response.data;
            this.open = true;
            this.title = "修改角色";
        }); */
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$confirm('是否确认删除角色编号为"' + userIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          // 调接口
          // return delRole(userIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      /* importTemplate().then(response => {
        this.download(response.msg);
      }); */
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 导出按钮操作 */
    handleExport() {
      // const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有角色数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
      }).then(function() {
          // 调接口导出表
          // return exportRole(queryParams);
      }).then(response => {
          this.download(response.msg);
      })
    },
    // 表单重置
    reset() {
      this.form = {
        nickName: null,
        userName: null,
        deptId: null,
        phonenumber: null,
        roleIds: [],
        status: "0",
        roleSort: 0,
      };
      // this.resetForm("form");
    },
    /** 弹框部分--------------------- */
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != undefined) {
            /* updateRole(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }); */
            this.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          } else {
            /* addRole(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }); */
            this.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
  }
};
</script>

<style scoped lang="scss">
// /deep/ 
</style>